namespace RBAC.Write.Api.Application.Handler.BomHandler
{
    using System;
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.BomManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.BomCommand;

    /// <summary>
    /// 新增BOM 处理器
    /// </summary>
    public class BomAddHandler : IRequestHandler<BomAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Bom> _bomRepo;
        private readonly IBaseRepository<Product> _productRepo;
        private readonly ILogger<BomAddHandler> _logger;

        public BomAddHandler(
            IBaseRepository<Bom> bomRepo,
            IBaseRepository<Product> productRepo,
            ILogger<BomAddHandler> logger)
        {
            _bomRepo = bomRepo;
            _productRepo = productRepo;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(BomAddCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                // 校验
                if (string.IsNullOrWhiteSpace(request.Name))
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "BOM名称不能为空", Data = 0 });
                if (request.ProductId <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "产品Id无效", Data = 0 });

                // 校验产品存在
                var product = _productRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = request.ProductId });
                if (product == null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "关联产品不存在", Data = 0 });

                // BOM 名称查重
                var nameExist = _bomRepo.GetFirstOrDefault("Name = @Name AND IsDeleted = 0", new { Name = request.Name!.Trim() });
                if (nameExist != null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "BOM名称已存在", Data = 0 });

                // 同一产品仅允许存在一个BOM，避免重复创建（产品Id查重）
                var productBomExist = _bomRepo.GetFirstOrDefault("ProductId = @ProductId AND IsDeleted = 0", new { ProductId = request.ProductId });
                if (productBomExist != null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "该产品已存在BOM，不允许重复创建", Data = 0 });

                // 生成BOM编码：BOM + yyMMddHHmmss（年保留两位）
                var code = "BOM" + DateTime.Now.ToString("yyMMddHHmmss");

                // 唯一性校验（编码）
                var exist = _bomRepo.GetFirstOrDefault("Code = @Code AND IsDeleted = 0", new { Code = code });
                if (exist != null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "BOM编码已存在，请重试", Data = 0 });

                var entity = new Bom
                {
                    Code = code,
                    Name = request.Name!.Trim(),
                    ProductId = request.ProductId,
                    ProductName = product.Name, // 以数据库中产品名称为准
                    Version = string.IsNullOrWhiteSpace(request.Version) ? "V1.0" : request.Version!.Trim(),
                    Unit = request.Unit,
                    RevisionNotes = string.IsNullOrWhiteSpace(request.RevisionNotes) ? "首次创建" : request.RevisionNotes!.Trim(),
                    Status = 0
                };
                if (!string.IsNullOrWhiteSpace(request.CreateUser))
                {
                    entity.CreateUser = request.CreateUser!;
                }

                var newId = _bomRepo.Create(entity);

                result.Code = newId > 0 ? APIEnums.Success : APIEnums.Fail;
                result.Msg = newId > 0 ? "新增BOM成功" : "新增BOM失败";
                result.Data = newId;
            }
            catch (OperationCanceledException)
            {
                _logger?.LogWarning("新增BOM被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "新增BOM异常: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "新增BOM异常: " + ex.Message;
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
